/**
 * @create 2022-04-05
 * @desc axios
 */

import type { BaseResponse } from '@src/types/axios';
import axios, { AxiosResponse, AxiosInstance, AxiosRequestConfig } from 'axios';
import { STATUS_CODE, HTTP_STATUS_CODE } from '@common/constant/const';
import { handleError } from '@common/utils/messages';

const tipError = (config?: AxiosRequestConfig, e?: Error | { message?: string }) => {
  if (!config?.silent) {
    handleError(e);
  }
};

const fetcher: AxiosInstance = axios.create({
  timeout: 30000,
});

fetcher.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

fetcher.interceptors.response.use(
  (response) => {
    const res: BaseResponse = response.data as BaseResponse;

    if (response.status !== HTTP_STATUS_CODE.success) {
      return Promise.reject(response);
    }

    if (res.code !== STATUS_CODE.success) {
      tipError(response.config, res);
      return Promise.reject(response);
    }

    return Promise.resolve(response);
  },
  (error) => {
    // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
    const response = (error?.response ?? {}) as AxiosResponse;
    const { status, config = {} } = response;

    switch (status) {
      case HTTP_STATUS_CODE.noFound:
        tipError(config, { message: '请求不存在' });
        break;
      default:
        tipError(config, { message: (response?.data as BaseResponse)?.message || '请求错误' });
    }

    return Promise.reject(response);
  },
);

export default fetcher;
